/*
 * @author Chris
 * @since 2023/2/6 17:28
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/2/6     Chris        the first version
 */
#include "8052.h"
#include "stdio.h"
#include "string.h"

unsigned char T0RH = 0;
unsigned char T0RL = 0;

int flag1s = 0;

void ConfigTimer0(unsigned char ms);

extern void Start18B20();

extern __bit Get18B20Temp(int *temp);

extern void InitLcd1602();

extern void Lcd1602Show(unsigned char x, unsigned char y, unsigned char *buf, unsigned char len);

int main() {
    EA = 1;
    ConfigTimer0(10);
    Start18B20();
    InitLcd1602();

    unsigned char tempBuf[10];
    while (1) {
        if (flag1s) {
            flag1s = 0;

            int temp = 0;
            if (Get18B20Temp(&temp)) {
                unsigned char intT = temp >> 4;
                unsigned char decT = temp & 0xF;

                sprintf(tempBuf, "%d.%d", intT, decT * 10 / 16);
                // tempBuf[3] = '.';
                // sprintf(tempBuf + 4, "%d", decT * 10 / 16);
                Lcd1602Show(0, 0, tempBuf, strlen(tempBuf));

                sprintf(tempBuf + 5, "%4X", temp);
                Lcd1602Show(7, 0, tempBuf + 5, 4);
            }

            Start18B20();
        }
    }
}

void ConfigTimer0(unsigned char ms) {
    TMOD = TMOD & 0xF0 | 0x01;
    unsigned long temp = 65536 - 11059200 * ms / 12 / 1000 + 12;
    T0RH = temp >> 8;
    T0RL = temp & 0xFF;
    TH0 = T0RH;
    TL0 = T0RL;

    ET0 = 1;
    TR0 = 1;
}

/**
 * 定时器 T0 中断服务函数
 */
void InterruptTimer0() __interrupt(1) {
    TH0 = T0RH;
    TL0 = T0RL;

    static int cnt = 0;

    if (cnt++ >= 100) {
        cnt = 0;
        flag1s = 1;
    }
}
